
import easyocr
import cv2
import warnings

def ocr_demo(image_path, languages=['ch_sim', 'en']):
    try:
        # 忽略模型加载时的警告
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            reader = easyocr.Reader(languages, gpu=False)  # 使用CPU模式
        
        # 读取图像
        img = cv2.imread(image_path)
        if img is None:
            raise FileNotFoundError(f"无法加载图像文件: {image_path}")

        # 执行OCR识别
        results = reader.readtext(img, detail=1)
        
        # 输出识别结果
        print("识别结果（坐标|文本|置信度）:")
        for (bbox, text, prob) in results:
            print(f"{bbox} | {text} | {prob:.2f}")

        # 可视化结果（可选）
        for (bbox, text, prob) in results:
            (tl, tr, br, bl) = bbox
            tl = (int(tl[0]), int(tl[1]))
            br = (int(br[0]), int(br[1]))
            cv2.rectangle(img, tl, br, (0, 255, 0), 2)
            cv2.putText(img, text, (tl[0], tl[1] - 10),
                        cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)
        
        cv2.imshow("OCR Result", img)
        cv2.waitKey(0)
        
    except Exception as e:
        print(f"发生错误: {str(e)}")
    finally:
        cv2.destroyAllWindows()

if __name__ == "__main__":
    ocr_demo("png.png")  # 替换为你的图片路径
